from .captcha.utils import gen_random_code
from .captcha.captcha import *
from django.http import JsonResponse
import base64
from django.core.cache import cache
import uuid


def getCaptcha(request):
    captcha_text = gen_random_code()
    image_data = Captcha.instance().generate(captcha_text)
    encodestr = str(base64.b64encode(image_data), 'utf-8')
    captchaId = uuid.uuid1()
    cache.set(captchaId, captcha_text.lower(), 2 * 60)  # 有效期为两分钟，验证码统一存储成小写
    return JsonResponse({'captcha_id': captchaId, 'captcha_img': encodestr})


def verifyCaptcha(id, captcha):
    if cache.has_key(id):
        if cache.get(id) == captcha.lower():
            return 1  # 验证码正确
        else:
            return 2  # 验证码错误
    else:
        return 3  # 验证码不存在,说明验证码已经过期
